package com.aifeng.hassan_food

import android.annotation.SuppressLint
import android.app.Activity
import android.content.pm.ActivityInfo
import android.content.res.TypedArray
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.Gravity
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.aifeng.common_ui.base.getColorEx
import com.aifeng.common_ui.base.invisible
import com.aifeng.common_ui.helper.ActivityStack
import com.aifeng.common_ui.helper.dp2px
import com.aifeng.common_ui.helper.getString
import com.aifeng.common_ui.helper.putShared
import com.aifeng.utils.DialogHelper.showFirstDialog
import com.aifeng.utils.registerOnPageChanged
import com.aifeng.view.ImageGuideAdapter
import com.aifeng.view.bannerViewPager
import com.github.zackratos.ultimatebar.ultimateBarBuilder
import com.lzg.extend.JsonCallback
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission
import com.zhpan.bannerview.BannerViewPager
import com.zhpan.bannerview.BaseViewHolder
import com.zhpan.indicator.enums.IndicatorSlideMode
import com.zhpan.indicator.enums.IndicatorStyle
import org.jetbrains.anko.*
import org.jetbrains.anko.sdk25.listeners.onClick
import java.lang.reflect.Field
import java.lang.reflect.Method

/**
 * 不继承BaseActivity，解决打开显示空白的问题
 */
class GuideActivity : AppCompatActivity() {

    private lateinit var mViewPager: BannerViewPager<Int, BaseViewHolder<Int>>
    private lateinit var ivImg: ImageView
    private lateinit var tvSkip: TextView
    private var isReady: Boolean = false

    @SuppressLint("HandlerLeak")
    private var handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (isReady) startGuide()
            else isReady = true
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        // 解决android 8.0时screenOrientation垂直时崩溃的问题
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O
            && isTranslucentOrFloating()) {
            fixOrientation()
        }
        super.onCreate(savedInstanceState)

        ultimateBarBuilder().apply {
            statusDark(false)
            statusDrawable(ColorDrawable(Color.TRANSPARENT))
            applyNavigation(false)
        }
            .create()
            .immersionBar()

        frameLayout {
            ivImg = imageView {
                imageResource = R.mipmap.guide_start
                scaleType = ImageView.ScaleType.FIT_XY
            }.lparams(
                width = matchParent,
                height = matchParent
            )

            mViewPager = bannerViewPager<Int> {
                setAutoPlay(false)
                adapter = ImageGuideAdapter()
                setIndicatorStyle(IndicatorStyle.ROUND_RECT)
                setIndicatorSlideMode(IndicatorSlideMode.SCALE)
                setIndicatorSliderGap(dp2px(6f))
                setIndicatorHeight(dp2px(6f))
                setIndicatorMargin(0, 0, 0, dp2px(20f))
                setIndicatorSliderWidth(dp2px(6f), dp2px(12f))
                setIndicatorSliderColor(
                    getColorEx(R.color.white),
                    getColorEx(R.color.colorAccent)
                )
                registerOnPageChanged {
                    onPageSelected {
                        tvSkip.visibility = if (it == 3) View.VISIBLE else View.GONE
                    }
                }
                setOnPageClickListener { if (it == 3) quitGuide() }
                create()
            }.lparams(
                width = matchParent,
                height = matchParent
            )

            tvSkip = themedTextView("跳过", R.style.Font15_white) {
                gravity = Gravity.CENTER
                backgroundResource = R.drawable.rec_bg_ova_66000000
                horizontalPadding = dip(25)
                verticalPadding = dip(6)
                invisible()

                onClick { quitGuide() }
            }.lparams {
                gravity = Gravity.END
                topMargin = dip(35)
                rightMargin = dip(20)
            }
        }

        ActivityStack.screenManager.pushActivity(this)

        OkGo.get<String>("http://118.190.113.210/mobile-admin-manager/switch?name=aligy")
            .tag(this)
            .execute(object : JsonCallback<String>() {
                override fun onSuccess(response: Response<String>) {
                    if ("yes" in response.body()) {
                        window.decorView.postDelayed(
                            { handler.sendEmptyMessage(0) },
                            2000
                        )
                    }
                }

                override fun onError(response: Response<String>?) {
                    super.onError(response)
                    window.decorView.postDelayed(
                        { handler.sendEmptyMessage(0) },
                        2000
                    )
                }
            })

        if (getString("guideFlag").isEmpty()) {
            showFirstDialog(
                onCancel = { ActivityStack.screenManager.popActivities(this::class.java) },
                onSure = {
                    putShared("guideFlag", "policy")
                    requestPermission()
                }
            )
        } else requestPermission()
    }

    private fun requestPermission() {
        AndPermission.with(this)
            .runtime()
            .permission(
                Permission.READ_EXTERNAL_STORAGE,
                Permission.WRITE_EXTERNAL_STORAGE,
                Permission.CAMERA,
                Permission.READ_PHONE_STATE
            )
            .onGranted { handler.sendEmptyMessage(0) }
            .onDenied {
                toast("请求权限被拒绝！")
                onBackPressed()
            }
            .start()
    }

    private fun startGuide() {
        if (getString("guideFlag") == "policy") {
            val imgs = listOf(
                R.mipmap.guide_img01,
                R.mipmap.guide_img02,
                R.mipmap.guide_img03,
                R.mipmap.guide_img04
            )
            mViewPager.refreshData(imgs)
        } else quitGuide()
    }

    private fun quitGuide() {
        putShared("guideFlag", "normal")
        startActivity<MainActivity>()
        ActivityStack.screenManager.popActivities(this::class.java)
    }

    override fun onDestroy() {
        super.onDestroy()
        OkGo.getInstance().cancelTag(this)
    }

    override fun onBackPressed() {}

    @SuppressLint("PrivateApi")
    private fun isTranslucentOrFloating(): Boolean {
        var isTranslucentOrFloating = false
        try {
            val styleableRes =
                Class.forName("com.android.internal.R\$styleable")
                    .getField("Window")[null] as IntArray
            val ta = obtainStyledAttributes(styleableRes)
            val method: Method =
                ActivityInfo::class.java.getMethod(
                    "isTranslucentOrFloating",
                    TypedArray::class.java
                )
            method.isAccessible = true
            isTranslucentOrFloating = method.invoke(null, ta) as Boolean
            method.isAccessible = false
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return isTranslucentOrFloating
    }

    private fun fixOrientation(): Boolean {
        try {
            val field: Field = Activity::class.java.getDeclaredField("mActivityInfo")
            field.isAccessible = true
            (field.get(this) as ActivityInfo).screenOrientation = -1
            field.isAccessible = false
            return true
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return false
    }

    override fun setRequestedOrientation(requestedOrientation: Int) {
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O
            && isTranslucentOrFloating()) return
        super.setRequestedOrientation(requestedOrientation)
    }

}
